<template>
	<view class=" content">
		<view class="top">
			<view class="top-left">
				<uni-easyinput prefixIcon="search" v-model="value" placeholder="请输入关键字" @input="getInput"
					@iconClick="iconClick">
				</uni-easyinput>
			</view>
			<view class="top-right">
				<text class="iconfont icon-dizhi1 text1"></text>
				<text class="text2" v-if="isShowMap" @click="closeMap">收起地图</text>
				<text class="text2" v-else @click="showMap">查看地图</text>
			</view>
		</view>
		<view class="middle" v-if="isShowMap">
			<map id="myMap" class="map" :scale="scale" joinCluster="true" name=" " :longitude="lgt" :latitude="lat"
				:markers="covers"></map>
		</view>
		<view class="fj">
			<view class="fj-title">
				附件餐厅
				<view class="active">

				</view>
			</view>

		</view>
		<view class="button">
			<scroll-view scroll-y="true" class="scroll-Y" :style="{ height: `${scrollProHei}px` }"
				@scrolltoupper="upper" @scrolltolower="lower" @scroll="scroll">


				<view class="scr " :class="{ active: activeIndex == item.id }" v-for="(item,index) in shopList"
					:key="item.id" @click="setActiveIndex(item,index)">
					<view class="scr-left" @click="toShopDetail">
						<image class="img" :src="imgUrl+item.storeImg"></image>
						<view class="ct">
							<text class="xq">餐厅详情</text><text class="xq1">></text>
						</view>
					</view>
					<view class="scr-right">
						<view class="title">
							<text class="w">{{item.shopName}}</text>
						</view>
						<view class="address">
							<text class="address-dis">1{{item.distance}}米</text><text
								class="address-detail">{{item.shopAddress}}</text>
						</view>
						<view class="yy">24小时营业</view>
					</view>
				</view>

				<view class="scr" style="height: 100px;">

				</view>
			</scroll-view>
		</view>

		<view class="toOrder" v-if="shopAddId!=0" @click="toShop">
			去点餐
		</view>
	</view>

</template>

<script setup>
	import {
		ref,
		onMounted,
		computed,
		reactive
	} from "vue"

	import {
		userInfo
	} from '../../stores/userInfo'

	let UserInfo = userInfo()

	let activeIndex = ref(0) //动态active

	let mapContext = null

	const scale = ref(15)

	let shopDetailData = ref({}) // 这是店铺id，用来获取店铺商品的
	let shopAddId = ref(0)
	//输入节流
	let throttleTimer = null; // 用于存储定时器的引用
	const throttleDelay = 500; // 节流的时间间隔（单位：毫秒）


	let covers = computed(() => {
		return shopList.value.map(item => {
			return {
				id: item.id,
				latitude: item.latitude,
				longitude: item.longitude,
				iconPath: UserInfo.getimgUrl() + item.storeImg, // 或使用 item.storeImg
				width: 32,
				height: 32,
				title: item.shopName,
				anchor: {
					x: 0.5,
					y: 1
				}, // 图标底部中心为锚点
				callout: {
					display: 'ALWAYS',
					content: `
			        📞电话：${item.phone}
			        🕒营业：${item.openTime || '全天'}
			      `,
					color: '#333333',
					fontSize: '12px',
					borderWidth: 1,
					borderColor: '#eeeeee',
					borderRadius: '8px',
					bgColor: '#ffffff',
					padding: '10px',
					boxShadow: '0 2px 6px rgba(0,0,0,0.1)'
				}

			}
		})
	})

	//搜索店铺
	let getInput = (e) => {
		if (throttleTimer) clearTimeout(throttleTimer);
		
		throttleTimer = setTimeout(() => {
			
			console.log(e, "店铺"); // 原始逻辑
			getshopListData({shopName:e})
			throttleTimer = null; // 执行完成后清空定时器
			
		}, throttleDelay);
	
	}


	//是否显示地图
	let isShowMap = ref(true)

	// 定义一个响应式变量来存储窗口高度
	let usableHeight = ref(0);

	let scrollProHei = ref(0);

	let value = ref("")
	// 22.836228,108.298517
	let lgt = ref(108.298517)
	let lat = ref(22.836228)

	let shopList = ref([]) // 店铺列表

	let src = ref('https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/shuijiao.jpg')

	let scroll = function(e) {
		// console.log(e)
		// this.old.scrollTop = e.detail.scrollTop
		// console.log(e, "这是滚动")
	}

	let iconClick = () => {
		console.log("搜索")
	}

	let toShop = () => {
		
		
		// console.log(shopDetailData.value)
		// uni.navigateTo({
		// 	url: "/pages/menu/menu"
		// })
		
		uni.navigateTo({
			url: "/pages/menu/menu",
			success: function(res) {
				// 通过eventChannel向被打开页面传送数据
				res.eventChannel.emit('accpetshopAddId', {
					data: shopDetailData.value
				})
			}
		})
	}



	let imgUrl = computed(() => {
		
		return UserInfo.getimgUrl()
	})




	// 处理标记点击
	const setActiveIndex = async (e, index) => {
		activeIndex.value = e.id
		shopAddId.value = e.id
		
		shopDetailData.value = e
		const marker = covers.value.find(item => item.id === e.id)
		// console.log(marker, "marker")
		// 方案1：平滑移动动画
		mapContext.moveToLocation({
			latitude: marker.latitude,
			longitude: marker.longitude,

			duration: 1500 // 动画时长（毫秒）

		})
		scale.value = 15


	}

	//去详情页
	let toShopDetail = () => {
		uni.navigateTo({
			url: "/pages/menu/shopDetail"
		})
	}


	const generateDynamicValue  = (
	  baseline = 266,
	  deviationRange = 800,
	  decimals = 0,
	  distribution = 'gaussian' // 可选项: uniform(默认)/gaussian
	) => {
	  let fluctuation
	  
	  // 选择分布算法
	  switch(distribution) {
	    case 'gaussian':
	      // 高斯分布（68%数值在±deviationRange/2范围内）
	      do {
	        const u = Math.random()
	        const v = Math.random()
	        fluctuation = (Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v)) * deviationRange / 2
	      } while(Math.abs(fluctuation) > deviationRange)
	      break;
	      
	    default: // uniform
	      fluctuation = (Math.random() * 2 - 1) * deviationRange
	  }
	  
	  const rawValue = baseline + fluctuation
	  return Math.max(0, Number(rawValue.toFixed(decimals)))
	}

	//显示隐藏地图
	let closeMap = () => {
		isShowMap.value = false
		scrollProHei.value += 200
	}
	//显示隐藏地图
	let showMap = () => {
		isShowMap.value = true
		scrollProHei.value -= 200
	}

	//获取店铺数据
	let getshopListData = async (data)=>{
		
		let res = await UserInfo.getShopStoreAddress(data)
		
		shopList.value = res
		shopList.value.map(item=>{
			
			item.distance = generateDynamicValue()
			console.log(item,"item")
		})
		//  shopList.value= res.map(item=>{
		// 	 console.log(item,"item")
		// 	 const newItem = { ...item }
		// 	 newItem.distance = generateDynamicValue()
		//  })
		
		// console.log(shopList.value,"shopList.value")
	}

	onMounted(async () => {
		uni.getSystemInfo({
			success: (res) => {
				const statusBarHeight = res.statusBarHeight;
				const navBarHeight = 44;
				usableHeight.value = res.windowHeight - (statusBarHeight + navBarHeight);
				scrollProHei.value = usableHeight.value - 200 - 10;
				// console.log("可用高度:", usableHeight.value, scrollProHei.value);
			}
		});
		
		getshopListData({})
		
		// console.log(UserInfo.ImgUrl,"地址")
		// console.log(res, '这是商品列表这边的')

		mapContext = uni.createMapContext('myMap')
	});
</script>

<style lang="scss">
	.content {
		position: relative;

		.top {
			padding: 10px;
			display: flex;
			justify-content: space-between;

			.top-left {
				width: 70%;
			}

			.top-right {
				display: flex;
				justify-content: center;
				align-items: center;
				width: 30%;

				.text2 {
					margin-left: 4px;
					font-size: 14px;

				}
			}
		}

		.middle {
			.map {
				width: 100%;
				height: 200px;
			}
		}

		.fj {
			font-size: 18px;
			font-weight: bolder;
			padding: 10px;
			height: 24px;

			.fj-title {
				position: relative;
				/* 标题本身也需要相对定位 */
				z-index: 1;

				/* 确保标题在横线上方 */
				.active {
					position: absolute;
					/* 使用绝对定位 */
					left: 9%;
					/* 横线水平居中 */
					transform: translateX(-50%);
					/* 精确调整横线到中心 */
					bottom: -8px;
					/* 调整横线距离标题下方的距离 */
					width: 32px;
					/* 横线的宽度 */
					height: 4px;
					/* 横线的高度 */
					background-color: red;
					/* 横线的颜色 */
				}
			}

		}

		.button {
			.scr {
				padding: 10px;
				display: flex;
				border: 4px solid white;
				/* 红色边框，宽度为2px */

				.scr-left {
					background-color: #ededed;
					width: 30%;

					border-radius: 0 0 10px 10px;
					padding-bottom: 4px;

					.img {
						width: 100%;
						height: 70px;
						background-color: #eeeeee;

					}

					.ct {
						margin-top: 5px;
						margin-bottom: 5px;
						display: flex;
						justify-content: center;
						align-items: center;

						.xq {
							font-size: 12px;
							margin-right: 4px;
						}
					}
				}

				.scr-right {
					margin-left: 10px;

					.title {
						font-weight: bold;
					}

					.address {
						margin-top: 8px;

						.address-dis {
							font-size: 14px
						}

						.address-detail {
							font-size: 14px;
							color: #6b6b6b;
							margin-left: 10px;

						}
					}

					.yy {
						font-size: 14px;
						margin-top: 8px;
					}
				}
			}
		}

		.scr.active {
			border: 4px solid red;
			/* 红色边框，宽度为2px */
			box-sizing: border-box;
			/* 确保边框不会影响布局 */
		}

		.toOrder {
			// 基础样式
			position: fixed; // 固定定位
			right: 19px; // 距离右侧 30px
			bottom: 15px; // 距离底部 30px
			// width: 150px; // 按钮宽度
			width: 90%;
			height: 50px; // 按钮高度
			background-color: red; // 背景颜色（橙红色）
			color: #ffffff; // 文字颜色（白色）
			font-size: 18px; // 字体大小
			font-weight: bold; // 字体加粗
			border: none; // 移除边框
			// border-radius: 25px; // 圆角
			box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); // 添加阴影效果
			cursor: pointer; // 鼠标悬停时显示手型
			transition: all 0.3s ease; // 添加过渡效果
			z-index: 999; // 确保按钮在其他内容之上
			align-items: center;
			justify-content: center;
			display: flex;
		}
	}

	.scroll-Y {
		height: 500px;
	}

	.scroll-view_H {
		white-space: nowrap;
		width: 100%;
	}

	.scroll-view-item {
		height: 300rpx;
		line-height: 300rpx;
		text-align: center;
		font-size: 36rpx;
	}

	.scroll-view-item_H {
		display: inline-block;
		width: 100%;
		height: 300rpx;
		line-height: 300rpx;
		text-align: center;
		font-size: 36rpx;
	}
</style>